import { Component, ReactNode } from "react";
import { Button, Popconfirm, Table, message, Input, Space,Tag } from "antd";
import { instance } from "../../utils/request";
import {SettingOutlined,SearchOutlined,FileAddFilled, ClearOutlined} from "@ant-design/icons";
import EditDictType from "../DictView/EditDictType";
import AddDictType from "../DictView/AddDictType";
import { Link } from 'react-router-dom';

const { Search } = Input;

class DictTypeList extends Component {
  state = {
    dataSource: [], // 添加初始化的dataSource属性
    total: 0, // 总条数
    pagenum: 1, // 当前页
    pagesize: 5, // 显示数量
    query: "", // 查询条件
    showAddDictDialog: false, // 是否隐藏
    showEditTypesDialog: false, // 是否隐藏
    editData: {}, 
    queryType:'',
    queryCode:''
  };
  loadData = () => {
    const params = {
      pagenum: this.state.pagenum,
      pagesize: this.state.pagesize,
      queryType: this.state.queryType,
      queryCode: this.state.queryCode,
    };

    instance.get("/dtypes", { params }).then((res) => {
      console.log(res.data.data.goods);
      this.setState({
        dataSource: res.data.data.data,
        total: res.data.data.total,
      });
    });
  };

  handleEdit = (record: any) => {
    // goods/:id 根据id 进行查询
    instance.get(`dtypes/${record}`).then((res) => {
      console.log('dtypes返回的数据',res.data.data[0])
      this.setState({
        editData: res.data.data[0],
        showEditTypesDialog: true,
      });
    });
  };

  // 22章
  showEditDialog = (falg: any) => {
    if (falg) {
      return (
          <EditDictType
              visible={this.state.showEditTypesDialog}
              closeModal={this.closeEditDialog}
              data={this.state.editData}
          ></EditDictType>
      );
    }
  };


  onSearch = () => {
 
    // 拿到输入框的值 ,记录结果
      let searchData = {
        queryType: this.state.queryType,
        queryCode: this.state.queryCode
      };
    // 将搜索条件转换成JSON格式并存储在sessionStorage中
    sessionStorage.setItem("searchData", JSON.stringify(searchData));
    this.loadData()
  };

  clearSearch =()=>{
    this.setState({
      queryType:'',
      queryCode: ''
    })
  
  }

  // 分页，点击页、显示数量
  changePage = (page: number, pagesize: number) => {
    this.setState({ pagenum: page, pagesize: pagesize }, () => {
      this.loadData();
    });
  };

  handleDelete = (id: any) => {
    instance.delete(`/dtypes/${id}`).then((res) => {
      if (res.data.meta.status === 200) {
        message.success("删除成功!");
        this.loadData();
      } else {
        message.error("删除失败!");
      }
    });
  };

  handleToSettgins=(record: any)=>{
    console.log(record)
  }

  // 添加商品
  handleAdd = () => {
    this.setState({ showAddDictDialog: true });
  };
  // 关闭添加窗口
  closeAddDialog = () => {
    this.setState({ showAddDictDialog: false }, () => {
      this.loadData();
    });
    // 重新进行更新刷新页面
  };
  closeEditDialog = () => {
    this.setState({ showEditTypesDialog: false }, () => {
      this.loadData();
    });
    // 重新进行更新刷新页面
  };

  // 组件加载完挂载
  componentDidMount() {
    // 取出搜索的值
    const searchDataStr = sessionStorage.getItem('searchData');
    if (searchDataStr) {
      // 把取到的JSON格式的转化为JS格式
      const searchData = JSON.parse(searchDataStr);
      if (searchData) {
        this.setState({
          queryCode: searchData.queryCode,
          queryType: searchData.queryType
        });
  
        // 完了之后记得把本地的数据清除掉
        sessionStorage.removeItem("searchData");
      }
    }
  
    this.loadData();
  }
  

  render() {
    const columns = [
      {
        title: "类型名称",
        dataIndex: "type_name",
        key: "type_name",
      },
      {
        title: "类型编码",
        dataIndex: "type_code",
        key: "type_code",
      },
      {
        title: "字典状态",
        dataIndex: "status",
        key: "status",
        render: (status: any) => (
            <Tag color={status === '0' ? 'green' : 'red'}>
              {status === '0' ? '正常' : '禁用'}
            </Tag>
        ),
      },
      {
        title: "创建人",
        dataIndex: "create_by",
        key: "create_by",
      },
      {
        title: "操作",
        key: "action",
        render: (record: any) => (
          <>
            <Link
                to={`/settings/${record.type_code}`}  // 使用URL参数传递record的id
            >
            <Button
                type="primary"
                style={{ marginRight: "10px" }}
            >
              字典配置<SettingOutlined />
            </Button>
            </Link>
            <Button
              onClick={() => {
                this.handleEdit(record.id);
              }}
              style={{ marginRight: "10px" }}
            >
              编辑
            </Button>
            <Popconfirm
              okText="确认"
              cancelText="取消"
              title="你确认要删除该记录嘛?"
              onConfirm={() => {
                this.handleDelete(record.id);
              }}
            >
              <Button type="primary">删除</Button>
            </Popconfirm>
          </>
        ),
      },
    ];
    return (
      <div>
        <Space style={{ marginBottom: 20, marginTop: 10 }}>
          类型名称:
          <Input
            size="large"
            placeholder="请输入类型名称"
            value={this.state.queryType}
            onChange={(e) => this.setState({ queryType: e.target.value })}
            allowClear
          />
            类型编码:
          <Input
             size="large"
            placeholder="请输入类型编码"
            value={this.state.queryCode}
            onChange={(e) => this.setState({ queryCode: e.target.value })}
            allowClear
          />
          <Button type="primary" size="large" onClick={this.onSearch}>
            搜索 <SearchOutlined />
          </Button>

        </Space>
        <Button
          style={{ marginTop: "7px", marginLeft: "10px" }}
          onClick={this.handleAdd}
          size="large"
          type="primary"
        >
          添加字典 <FileAddFilled/>
        </Button>

         <Button style={{marginLeft: '15px'}} type="primary" size="large" onClick={this.clearSearch}>
            清空条件 <ClearOutlined />
          </Button>

        <Table
          dataSource={this.state.dataSource}
          columns={columns}
          rowKey="goods_id"
          pagination={{
            pageSize: this.state.pagesize,
            defaultCurrent: this.state.pagenum,
            onChange: this.changePage,
            total: this.state.total,
          }}
        />
       <AddDictType
          close={this.closeAddDialog}
          visible={this.state.showAddDictDialog}
        />
        {this.showEditDialog(this.state.showEditTypesDialog)}
      </div>
    );
  }
}

export default DictTypeList;
